﻿package GameUtils 
{	
	import MySQL.MySQLProvider;	
	
	import social.VKontakte.VKProvider;
	import social.VKontakte.VKEvents;
	import social.SocialDataEvent;
	
	import GameUtils.GameDataEvent;	
	
	import Core.PlayerInfo;
	
	import flash.events.EventDispatcher;				
	import social.VKontakte.VKUserFields;
	import social.VKontakte.VKUserRequest;
	import social.VKontakte.VKProfileEvent;
	
	public class UserLoader extends EventDispatcher
	{
		public const USER_LOADED:String = 'USER_LOADED';
		
		private var FDBProvider:MySQLProvider;
		private var FVKProvider:VKProvider;		
		private var FProfile:PlayerInfo;		
		
		public function UserLoader(ADB:MySQLProvider, AVK:VKProvider):void
		{
			FDBProvider = ADB;
			FVKProvider = AVK;
		}
		
		public function Load(AUID:String):void
		{
			FProfile = new PlayerInfo();
			FProfile.UID = AUID;
			
			FDBProvider.LoadPlayerInfo(AUID);
			FDBProvider.addEventListener(FDBProvider.PLAYER_INFO_LOADED, OnMySQLProfileLoaded);
		}
		
		private function OnMySQLProfileLoaded(e:GameDataEvent):void
		{
			FDBProvider.removeEventListener(FDBProvider.PLAYER_INFO_LOADED, OnMySQLProfileLoaded);
			FVKProvider.addEventListener(VKEvents.VK_PROFILE_LOADED, OnVKProfileLoaded);
			
			FProfile.Fill(e.Data as XML);
			
			var vRequest:VKUserRequest = new VKUserRequest(FProfile.UID);
			vRequest.Add(VKUserFields.PhotoMedium);			
			FVKProvider.RequestUserInfo(vRequest);
		}
		
		private function OnVKProfileLoaded(e:VKProfileEvent):void
		{
			FVKProvider.removeEventListener(VKEvents.VK_PROFILE_LOADED, OnVKProfileLoaded);
			
			FProfile.Photo = e.VKProfile.PhotoMedium;
			var vEvent:GameDataEvent = new GameDataEvent(USER_LOADED);
			vEvent.Data = FProfile;
			dispatchEvent(vEvent);
		}
	}	
}
